//
//  BIZCCLiveRoomViewController.m
//  biz
//
//  Created by zhangfuwei on 2017/3/28.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZCCLiveRoomViewController.h"
// Cell
#import "BIZLiveRoomTableViewCell.h"
#import "BIZLiveRoomTableViewCellNew.h"
// third
#import <AVFoundation/AVFoundation.h>
#import "FSDropDownMenu.h"
#import "CCSDK/RequestData.h"
#import "CCSDK/CCLiveUtil.h"
#import "Dialog.h"
#import "Utility.h"
#import "BIZCCLiveNavBarLeftButton.h"

//  customView
#import "BIZCCLiveSwitchView.h"
#import "BIZCCLiveNavbarViews.h"


//[em2_01]
#define FACE_NAME_HEAD  @"[em2_"
// 表情转义字符的长度（ [em2_占5个长度，xx占2个长度，]占一个长度,共8个长度 ）
#define FACE_NAME_LEN   8
#define FACE_COUNT_ALL  20
#define FACE_COUNT_ROW  4
#define FACE_COUNT_CLU  5
#define FACE_ICON_SIZE  44
#define IMGWIDTH        28.0f

// Navbar高度
static CGFloat kNavBarH = 64;

// 直播视频高度
static CGFloat kVideoFrameH = 248;
// 切换slider的高度
static CGFloat kSliderViewH = 30;

//  输入视图的高度
static CGFloat kInputViewH = 65;
//  视图间距
static CGFloat kViewMargin = 15;
//  输入textView视图 和 发送按钮 的高度
static CGFloat kInputViewItemsH = 40;
//  输入视图中按钮的宽度
static CGFloat kInputSendBtnW = 80;
/*占位字符*/
static NSString *const kDefaultPlaceHolder = @"请输入消息内容......";

@interface BIZCCLiveRoomViewController () <FSDropDownMenuDataSource,FSDropDownMenuDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UITextViewDelegate,UIAlertViewDelegate,RequestDataDelegate>

@property (strong,nonatomic) RequestData                *requestData;
@property (assign,nonatomic) CGRect                     videoFrame;
@property (assign,nonatomic) CGRect                     docFrame;
@property (strong,nonatomic) UIView                     *videoParent;
@property (strong,nonatomic) UIView                     *docParent;
@property (strong,nonatomic) UIView                     *bgview;
@property (strong,nonatomic) UIView                     *pptView;
@property (strong,nonatomic) UIView                     *overlayView;
@property (strong,nonatomic) UIActivityIndicatorView    *activityIndicatorView;
@property (strong,nonatomic) UITapGestureRecognizer     *singleTap;
@property (strong,nonatomic) UITapGestureRecognizer     *doubleTap;
@property (strong,nonatomic) UISegmentedControl         *segment;
/** 类navbar控件 */
@property (nonatomic, strong) BIZCCLiveNavbarViews *navbarView;

/** switchView */
@property (nonatomic, strong) BIZCCLiveSwitchView *switchView ;
/** SwitchSelectedIndx */
@property (nonatomic, assign) NSInteger selectedIndx;
/** 房间名 */
@property (nonatomic, copy) NSString *roomName;

@property (strong,nonatomic) UIScrollView               *scrollView;
@property (strong,nonatomic) UITableView                *chatTableView;
@property (strong,nonatomic) UITableView                *QATableView;
@property (strong,nonatomic) UIView                     *lianmaiView;

@property (assign,nonatomic) CGFloat                    width;
@property (assign,nonatomic) CGFloat                    height;
@property (assign,nonatomic) CGFloat                    tableViewH;
@property (assign,nonatomic) BOOL                       isLandscapeRight;
@property (assign,nonatomic) BOOL                       isPublicChat;

@property (copy,nonatomic) NSString                     *userId;
@property (copy,nonatomic) NSString                     *roomId;
@property (copy,nonatomic) NSString                     *name;
@property (copy,nonatomic) NSString                     *token;
@property (copy,nonatomic) NSString                     *viewerId;

@property (strong,nonatomic) NSMutableArray             *firstArr;
@property (strong,nonatomic) NSMutableArray             *secArr;
@property (strong,nonatomic) NSArray                    *currentArr;
@property (assign,nonatomic) NSInteger                  indexPre;

@property (strong,nonatomic) NSMutableArray             *chatArr;
@property (strong,nonatomic) NSMutableDictionary        *QADic;
@property (strong,nonatomic) NSMutableArray             *keysArr;

@property (assign,nonatomic) NSInteger                  lineLimit;
@property (strong,nonatomic) NSMutableArray             *array;
@property (assign,nonatomic) NSInteger                  secondToEnd;
@property (strong,nonatomic) NSTimer                    *timer;
@property (assign,nonatomic) NSInteger                  hiddenDelaySeconds;

@property (assign,nonatomic) BOOL                       isEmojjBoardShow;
@property (assign,nonatomic) BOOL                       isSystemBoardShow;
@property (assign,nonatomic) BOOL                       isButtonPauseType;

@property (strong,nonatomic) UIButton                   *keyboardButton;
@property (strong,nonatomic) UIButton                   *keyboardLandscapeButton;

@property (strong,nonatomic) UIButton                   *chatButton;
@property (strong,nonatomic) UIButton                   *chatLandscapeButton;

@property (strong,nonatomic) UIView                     *chatInputBackView;
@property (strong,nonatomic) UIView                     *QAInputBackView;
@property (strong,nonatomic) UIView                     *chatLandscapeInputBackView;

@property (strong,nonatomic) UITextView                 *chatTextView;
@property (strong,nonatomic) UITextView                 *QATextView;
@property (strong,nonatomic) UITextView                 *chatLandscapeTextView;

@property (strong,nonatomic) UIButton                   *chatSendBtn;
@property (strong,nonatomic) UIButton                   *QASendBtn;
@property (strong,nonatomic) UIButton                   *chatLandscapeSendBtn;

@property (strong,nonatomic) UIView                     *chatInputView;
@property (strong,nonatomic) UIView                     *chatLandscapeInputView;

@property (assign,nonatomic) CGRect                     chatInputViewSize;
@property (assign,nonatomic) CGRect                     chatLandscapeInputViewSize;
@property (strong,nonatomic) UILabel                    *informationLabel;

@property (strong,nonatomic) UIButton                   *zoomBtn;
@property (strong,nonatomic) UIButton                   *zoomLandscapeBtn;

@property (assign,nonatomic) NSInteger                  templateType;
@property (strong,nonatomic) UILabel                    *lianmaiLabel;
@property (strong,nonatomic) UIButton                   *lianmaiAVBtn;
@property (strong,nonatomic) UIButton                   *disconnectLianmaiBtn;
@property (strong,nonatomic) UIView                     *localView;
@property (strong,nonatomic) UIView                     *remoteView;
@property (strong,nonatomic) UILabel                    *information;
@property (assign,nonatomic) NSTimeInterval             currenttime;
@property (strong,nonatomic) NSTimer                    *connectTimer;
@property (strong,nonatomic) NSTimer                    *roomContextTimer;
@property (assign,nonatomic) NSInteger                  status;
@property (copy,nonatomic)   NSString                   *videosizeStr;
@property (strong,nonatomic) UIButton                   *activityBtn;
@property (strong,nonatomic) NSMutableArray             *secRoadKeyArray;
@property (strong,nonatomic) FSDropDownMenu             *menu;
/** <#note#> */
@property (nonatomic, assign) BOOL allowRotate;

@end

@implementation BIZCCLiveRoomViewController

- (BOOL)shouldAutorotate{
    if (_allowRotate) {
        _allowRotate = NO;
        return YES;
    }
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

#pragma mark life-Cycle
- (id)initWithUserId:(NSString *)userId RoomId:(NSString *)roomId ViewerName:(NSString *)name ViewerToken:(NSString *)token roomName:(NSString *)roomName
{
    if ( self = [super init] )
    {
        _userId = userId;
        _roomId = roomId;
        _name = name;
        _token = token;
        
        _chatArr = [[NSMutableArray alloc] init];
        _QADic   = [[NSMutableDictionary alloc] init];
        _keysArr  = [[NSMutableArray alloc] init];
        
        _lineLimit = (self.view.frame.size.width - 64) / (IMGWIDTH * 1.5);
        _secondToEnd = 8.0f;
        _array = [[NSMutableArray alloc] init];
    
        _isLandscapeRight = false;
        _isPublicChat = true;
        _isEmojjBoardShow = false;
        _isSystemBoardShow = false;
        _roomName = roomName;
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    [self addObservers];
    
    _width = self.view.frame.size.width;
    _height = self.view.frame.size.height;
    
    // 设置全局直播器frame
    _videoFrame  = CGRectMake(0, kNavBarH ,_width,kVideoFrameH);
    
    //  scrollView的frame
    CGFloat docFrameY = kVideoFrameH + kNavBarH;
    _docFrame    = CGRectMake(0, docFrameY , _width, _height- docFrameY - kInputViewH);
    
    //  直播视频背景图层
    _bgview = [[UIView alloc] initWithFrame:_videoFrame];
    [_bgview setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:_bgview];
    
    UIFont *font = [UIFont systemFontOfSize:25];
    _informationLabel = [[UILabel alloc] initWithFrame:_bgview.bounds];
    _informationLabel.backgroundColor = [UIColor clearColor];
    _informationLabel.font = font;
    _informationLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _informationLabel.textAlignment = NSTextAlignmentCenter;
    _informationLabel.textColor = [UIColor grayColor];
    _informationLabel.numberOfLines = 1;
    _informationLabel.text = @"直播已停止";
    _informationLabel.center = CGPointMake(CGRectGetMidX(_bgview.bounds), CGRectGetMidY(_bgview.bounds));
    [_bgview addSubview:_informationLabel];
    [_informationLabel setHidden:YES];
    
    //  切换聊天,问答模式
    _switchView = [[BIZCCLiveSwitchView alloc] initWithSwitchBlock:[self returnSwitchBlock]];
    _switchView.frame = CGRectMake(0,docFrameY,Main_Screen_Width, kSliderViewH+kViewMargin);
    
    _pptView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _docFrame.size.width, _docFrame.size.height)];
    [_pptView setBackgroundColor:[UIColor clearColor]];

    [_scrollView addSubview:_pptView];

    [self.view addSubview:_switchView];
    
    _videoParent = _bgview;
    _docParent   = _pptView;
    _requestData = [[RequestData alloc] initWithUserId:_userId RoomId:_roomId ViewerName:_name ViewerToken:_token setDocParent:_docParent setDocFrame:CGRectMake(0, 0, _docFrame.size.width, _docFrame.size.height) playerParent:_videoParent playerFrame:_videoFrame security:YES];
    _requestData.delegate = self;
    [self setupConfigInfo];
    [self initUI];
        
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 关闭 IQKeyboard,自己监听调起键盘的通知
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    [self setNavigationItems];
    [self loadNavBarViews];

    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 关闭 IQKeyboard,自己监听调起键盘的通知
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.automaticallyAdjustsScrollViewInsets = YES;
}

/// 使用颜色填充图片
- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}

- (void) addObservers {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isPreparingToPlayNoti:)
                                                 name:CCMovieIsPreparingToPlayNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackStateDidChange:)
                                                 name:CCMoviePlayStateChangedNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieLoadStateDidChange:)
                                                 name:CCMovieLoadStateChangedNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification  object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification  object:nil];
}

- (void)onBackClick {
    [self exitMessage];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UI初始化
- (void)setupConfigInfo {
    _selectedIndx = 1;
}

- (void)initUI {
//    [self setupBackGroudView];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ccLiveRoom_BG"]];
    [self addActivityIndicatorView];

    // 加载播放器覆盖视图，它作为所有空间的父视图。
    _overlayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _videoFrame.size.width, _videoFrame.size.height)];
    _overlayView.backgroundColor = [UIColor clearColor];
    
    _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    _singleTap.numberOfTapsRequired = 1;
    [_overlayView addGestureRecognizer:_singleTap];
    _doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap)];
    _doubleTap.numberOfTapsRequired = 2;
    [_overlayView addGestureRecognizer:_doubleTap];
    
    //全屏按钮
    _zoomLandscapeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _zoomLandscapeBtn.frame = CGRectMake(5,5,50,50);
    [_zoomLandscapeBtn addTarget:self action:@selector(handleDoubleTap) forControlEvents:UIControlEventTouchUpInside];
    _zoomLandscapeBtn.tag = 103;
    [_zoomLandscapeBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [_zoomLandscapeBtn setTintColor:[UIColor clearColor]];
    [_overlayView addSubview:_zoomLandscapeBtn];
    [_zoomLandscapeBtn setHidden:YES];
    
    [_bgview addSubview:_overlayView];
    
    _tableViewH = _height - (kVideoFrameH+kViewMargin+kSliderViewH+kInputViewH + kNavBarH);
    _chatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kSliderViewH + kViewMargin+kVideoFrameH + kNavBarH, _width ,_tableViewH) style:UITableViewStylePlain];
    _chatTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, kViewMargin)];
    _chatTableView.backgroundColor = [UIColor clearColor];
    _chatTableView.delegate = self;
    _chatTableView.dataSource = self;
    _chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _chatTableView.tag = 1;
    //    _chatTableView.estimatedRowHeight = 30;
    //    _chatTableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.view addSubview:_chatTableView];

    //全屏按钮
    [self loadZoomButton];
    
    [self loadLandscapeInputBackView];
    
    [self loadChatInputBackView];
    
    [self loadLianMaiViews];
}

// 加载全屏输入视图
- (void)loadLandscapeInputBackView {
    
    _chatLandscapeInputBackView = [[UIView alloc]initWithFrame: CGRectMake(0, self.view.frame.size.width - kInputViewH, self.view.frame.size.height, kInputViewH)];
    
    _chatLandscapeInputBackView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ccLiveRoom_BG"]];
    _chatLandscapeInputBackView.tag = 101;
    [_overlayView addSubview:_chatLandscapeInputBackView];
    
    
    //输入框
    CGFloat inputTextViewY = (kInputViewH - kInputViewItemsH) /2;

    _chatLandscapeTextView = [[UITextView alloc] initWithFrame:CGRectMake(kViewMargin, inputTextViewY , self.view.frame.size.height - (kInputSendBtnW + kViewMargin *3), kInputViewItemsH)];
    _chatLandscapeTextView.text = kDefaultPlaceHolder;
    _chatLandscapeTextView.textColor = HEXCOLOR(0xcecece);//设置textview里面的字体颜色
    
    _chatLandscapeTextView.layer.cornerRadius = kInputViewItemsH/2;
    _chatLandscapeTextView.clipsToBounds = YES;
    _chatLandscapeTextView.textAlignment = NSTextAlignmentLeft;
    _chatLandscapeTextView.showsHorizontalScrollIndicator = NO;
    _chatLandscapeTextView.showsVerticalScrollIndicator = NO;
    _chatLandscapeTextView.textContainerInset = UIEdgeInsetsMake(10, 15, 10,15);
    


    _chatLandscapeTextView.font = [UIFont systemFontOfSize:13];//设置字体名字和字体大小
    _chatLandscapeTextView.delegate = self;//设置它的委托方法
    _chatLandscapeTextView.backgroundColor = [UIColor whiteColor];//设置它的背景颜色
    _chatLandscapeTextView.returnKeyType = UIReturnKeyDefault;//返回键的类型
    _chatLandscapeTextView.keyboardType = UIKeyboardTypeDefault;//键盘类型
    _chatLandscapeTextView.scrollEnabled = YES;//是否可以拖动
    _chatLandscapeTextView.tag = 5;
    _isPublicChat = true;
    _chatLandscapeTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适应高度
    [_chatLandscapeInputBackView addSubview:_chatLandscapeTextView];//加入到整个页面中
    [_chatLandscapeInputBackView setHidden:YES];
    
    //发送
    CGFloat sendBtnX = self.view.frame.size.height - (kInputSendBtnW + kViewMargin );
    _chatLandscapeSendBtn = [[UIButton alloc]initWithFrame:CGRectMake(sendBtnX, inputTextViewY, kInputSendBtnW, kInputViewItemsH)];
    _chatLandscapeSendBtn.backgroundColor = HEXCOLOR(0xEEB82E);
    _chatLandscapeSendBtn.layer.cornerRadius = kInputViewItemsH/2;
    _chatLandscapeSendBtn.clipsToBounds = YES;
    [_chatLandscapeSendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [_chatLandscapeSendBtn addTarget:self action:@selector(clickSenBtnToSendMessage) forControlEvents:UIControlEventTouchUpInside];
    [_chatLandscapeInputBackView addSubview:_chatLandscapeSendBtn];

}

- (void)setupBackGroudView {
    
//    CGRect rect = CGRectMake(0,0, _width ,Main_Screen_Height-kVideoFrameH);
    CGRect rect = self.view.bounds;
    //创建CGContextRef
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef gc = UIGraphicsGetCurrentContext();
    
    //创建CGMutablePathRef
//    CGMutablePathRef path = CGPathCreateMutable();
    CGPathRef path1 = CGPathCreateWithRoundedRect(rect, 0, 0, nil);
    //绘制Path
//    CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
//    CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));
//    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMaxY(rect));
//    CGPathCloseSubpath(path);
    
    //绘制渐变
    [self drawLinearGradient:gc path:path1 startColor:COLOR_CCLIVEINPUTVIEW_BLUE1.CGColor endColor:COLOR_CCLIVEINPUTVIEW_BLUE2.CGColor];
    
    //注意释放CGMutablePathRef
    CGPathRelease(path1);
    
    //从Context中获取图像，并显示在界面上
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
    [self.view insertSubview:imgView atIndex:0];
    
}

- (void)drawLinearGradient:(CGContextRef)context
                      path:(CGPathRef)path
                startColor:(CGColorRef)startColor
                  endColor:(CGColorRef)endColor
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };
    
    NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
    
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    
    
    CGRect pathRect = CGPathGetBoundingBox(path);
    
    //具体方向可根据需求修改
    CGPoint startPoint = CGPointMake(CGRectGetMaxX(pathRect), CGRectGetMinY(pathRect));
    CGPoint endPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMaxY(pathRect));
    
    CGContextSaveGState(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGContextRestoreGState(context);
    
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

//  添加渐变色
- (void)getgradientRampForBgView {
    CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
    
    gradientLayer.colors = @[(__bridge id)COLOR_CCLIVEINPUTVIEW_BLUE1.CGColor,(__bridge id)COLOR_CCLIVEINPUTVIEW_BLUE2.CGColor];
    
    //位置x,y    自己根据需求进行设置   使其从不同位置进行渐变
    
    gradientLayer.startPoint = CGPointMake(1, 0);
    
    gradientLayer.endPoint = CGPointMake(1, 1);
    
    gradientLayer.frame = CGRectMake(0, 0, CGRectGetWidth(_chatTableView.frame), CGRectGetHeight(_chatTableView.frame));
    
    [_chatTableView.backgroundView.layer addSublayer:gradientLayer];
}

// 加载聊天输入视图
- (void)loadChatInputBackView {
    
    _chatInputBackView = [[UIView alloc]initWithFrame:CGRectMake(0, _height-kInputViewH,_width,kInputViewH)];
    _chatInputBackView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"ccLiveRoom_BG"]];
    [self.view addSubview:_chatInputBackView];
    
    //输入框
    CGFloat inputTextViewY = (kInputViewH - kInputViewItemsH) /2;
    CGFloat inputTextViewW = _width -(kInputSendBtnW + kViewMargin *3 );
    _chatTextView = [[UITextView alloc] initWithFrame:CGRectMake(kViewMargin, inputTextViewY , inputTextViewW, kInputViewItemsH)]; //初始化大小并自动释放
    _chatTextView.layer.cornerRadius = kInputViewItemsH/2;
    _chatTextView.clipsToBounds = YES;
    _chatTextView.textAlignment = NSTextAlignmentLeft;
    _chatTextView.showsHorizontalScrollIndicator = NO;
    _chatTextView.showsVerticalScrollIndicator = NO;
    _chatTextView.textContainerInset = UIEdgeInsetsMake(10, 15, 10,15);
    _chatTextView.text = @"请输入消息内容......";
    _chatTextView.textColor = HEXCOLOR(0xcecece);//设置textview里面的字体颜色
    _chatTextView.font = [UIFont systemFontOfSize:13];//设置字体名字和字体大小
    _chatTextView.delegate = self;//设置它的委托方法
    _chatTextView.backgroundColor = [UIColor whiteColor];//设置它的背景颜色
    _chatTextView.returnKeyType = UIReturnKeyDefault;//返回键的类型
    _chatTextView.keyboardType = UIKeyboardTypeDefault;//键盘类型
    _chatTextView.scrollEnabled = YES;//是否可以拖动
    //    _chatTextField.placeholder = @"公聊";
    _chatTextView.tag = 2;
    _isPublicChat = true;
    _chatTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适应高度
    [_chatInputBackView addSubview:_chatTextView];//加入到整个页面中
    
    //发送
    CGFloat sendBtnX = _width - (kInputSendBtnW + kViewMargin );
    _chatSendBtn = [[UIButton alloc]initWithFrame:CGRectMake(sendBtnX, inputTextViewY, kInputSendBtnW, kInputViewItemsH)];
    
    _chatSendBtn.backgroundColor = HEXCOLOR(0xEEB82E);
    _chatSendBtn.layer.cornerRadius = kInputViewItemsH/2;
    _chatSendBtn.clipsToBounds = YES;
    
    [_chatSendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [_chatSendBtn addTarget:self action:@selector(clickSenBtnToSendMessage) forControlEvents:UIControlEventTouchUpInside];
    [_chatInputBackView addSubview:_chatSendBtn];

}

// 设置导航控制器左右两侧item
- (void)setNavigationItems {
    
//    BIZCCLiveNavBarLeftButton *leftBtn = [[BIZCCLiveNavBarLeftButton alloc] initWithFrame:CGRectMake(0, 0, 120, 40)];
//    [leftBtn setBackgroundImage:[UIImage imageNamed:@"ccLiveRoom_buttonBg"] forState:UIControlStateNormal];
//    leftBtn.userM = nil;
//    leftBtn.roomName = _roomName;
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
//    self.navigationItem.leftBarButtonItem = leftItem;
//    
//    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
//    [rightBtn setImage:[UIImage imageNamed:@"ccLiveRoom_cancel"] forState:UIControlStateNormal];
//    [rightBtn addTarget:self action:@selector(onBackClick) forControlEvents:UIControlEventTouchUpInside];
//    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    // MARK:不符合要求

//    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
//    [leftBtn setImage:[UIImage imageNamed:@"ccLiveRoom_laba"] forState:UIControlStateNormal];
//    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
//    [rightBtn setImage:[UIImage imageNamed:@"ccLiveRoom_close"] forState:UIControlStateNormal];
//    [rightBtn addTarget:self action:@selector(onBackClick) forControlEvents:UIControlEventTouchUpInside];
    
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ccLiveRoom_laba"] style:UIBarButtonItemStylePlain target:nil action:nil];
//    UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//    UIBarButtonItem *titleItem = [[UIBarButtonItem alloc] initWithTitle:_roomName style:UIBarButtonItemStylePlain target:nil action:nil];
//    
//    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ccLiveRoom_close"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackClick)];
//
//
//    self.navigationItem.leftBarButtonItems = @[leftItem,flexItem,titleItem,flexItem,rightItme];
    self.navigationController.navigationBar.backItem.hidesBackButton = YES;
}

- (void)loadNavBarViews {
    MJWeakSelf;
    _navbarView = [[BIZCCLiveNavbarViews alloc] initWithRoomName:_roomName backBlock:^{
        
        [weakSelf onBackClick];
    }];
    _navbarView.frame = CGRectMake(0, 0, Main_Screen_Width, kNavBarH);
    
    [self.view addSubview:_navbarView];
}
// 加载连麦视图
- (void)loadLianMaiViews {
    //连麦显示文字
    _lianmaiView = [[UIView alloc] initWithFrame:CGRectMake(_width * 3, 0, _width, _tableViewH)];
    [_lianmaiView setBackgroundColor:[UIColor clearColor]];
//    [_scrollView addSubview:_lianmaiView];
    
    CGSize lianmaiSize = _lianmaiView.frame.size;
    
    _lianmaiLabel = [[UILabel alloc] init];
    _lianmaiLabel.frame = CGRectMake(0, lianmaiSize.height * 4 / 9,lianmaiSize.width, lianmaiSize.height / 9);
    _lianmaiLabel.backgroundColor = [UIColor clearColor];
    _lianmaiLabel.font = [UIFont systemFontOfSize:18];
    _lianmaiLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _lianmaiLabel.textAlignment = NSTextAlignmentCenter;
    _lianmaiLabel.textColor = [UIColor blackColor];
    _lianmaiLabel.numberOfLines = 1;
    _lianmaiLabel.text = @"主播未开启连麦功能";
    [_lianmaiView addSubview:_lianmaiLabel];
    
    //挂断连麦
    _disconnectLianmaiBtn = [[UIButton alloc]initWithFrame:CGRectMake(lianmaiSize.width * 5 / 18, lianmaiSize.height * 4 / 9,lianmaiSize.width * 4 / 9, lianmaiSize.height / 9)];
    [_disconnectLianmaiBtn setTitle:@"挂断视频连麦" forState:UIControlStateNormal];
    [_disconnectLianmaiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_disconnectLianmaiBtn setBackgroundColor:[UIColor redColor]];
    [_disconnectLianmaiBtn addTarget:self action:@selector(disConnectSpeak) forControlEvents:UIControlEventTouchUpInside];
    [_lianmaiView addSubview:_disconnectLianmaiBtn];
    _disconnectLianmaiBtn.hidden = YES;
    
    //申请视频连麦
    _lianmaiAVBtn = [[UIButton alloc]initWithFrame:CGRectMake(lianmaiSize.width * 5 / 18, lianmaiSize.height * 5 / 9,lianmaiSize.width * 4 / 9, lianmaiSize.height / 9)];
    [_lianmaiAVBtn setTitle:@"申请视频连麦" forState:UIControlStateNormal];
    [_lianmaiAVBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_lianmaiAVBtn setBackgroundColor:[UIColor colorWithRed:22/255.0 green:155/255.0 blue:213/255.0 alpha:1.0]];
    [_lianmaiAVBtn addTarget:self action:@selector(requestAVMessage) forControlEvents:UIControlEventTouchUpInside];
    [_lianmaiView addSubview:_lianmaiAVBtn];
    _lianmaiAVBtn.hidden = YES;
    
}

-(void)requestAVMessage {
    [_requestData gotoConnectWebRTC];
}

/*
 *  @brief 当前是否可以连麦
 */
- (void)whetherOrNotConnectWebRTCNow:(BOOL)connect {
    if(connect == YES) {
        _disconnectLianmaiBtn.hidden = YES;
        _lianmaiAVBtn.hidden = YES;
        _lianmaiLabel.hidden = NO;
        _lianmaiLabel.text = @"视频连麦申请中";
        
        [_requestData requestAVMessageWithLocalView:self.localView];
        
        CGRect viewRect = self.localView.frame;
        self.information.frame = CGRectMake(0, 0,viewRect.size.width, viewRect.size.height / 7);
        self.information.text = @"申请中";
        [self.localView addSubview:self.information];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"连麦失败" message:@"网络状况不佳" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alert show];
    }
}

-(void)disConnectSpeak {
    [_requestData disConnectSpeak];
}

- (void)loadZoomButton {
    _zoomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _zoomBtn.frame = CGRectMake(_overlayView.frame.size.width - 37,_overlayView.frame.size.height - 35,30,30);
    [_zoomBtn addTarget:self action:@selector(handleDoubleTap) forControlEvents:UIControlEventTouchUpInside];
    [_zoomBtn setBackgroundImage:[UIImage imageNamed:@"zoomin1"] forState:UIControlStateNormal];
    [_zoomBtn setTintColor:[UIColor clearColor]];
    _zoomBtn.tag = 103;
    [_overlayView addSubview:_zoomBtn];
}

- (BIZCCLiveSwitchViewSwitchBlock)returnSwitchBlock {
    BIZCCLiveSwitchViewSwitchBlock block = nil;
    __weak BIZCCLiveRoomViewController *weakSelf = self;
    block = ^(NSInteger idx){
        _selectedIndx = idx;
        
        [weakSelf.view endEditing:YES];
        [weakSelf scrollChatTableViewToBottom];
    };
    return block;
}

- (void)startAnimating {
    [_bgview bringSubviewToFront:_activityIndicatorView];
    [_activityIndicatorView startAnimating];
}

- (void)addActivityIndicatorView {
    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatorView.center = CGPointMake(CGRectGetMidX(_videoFrame), _videoFrame.size.height / 2);
    [_bgview addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];
    
    _activityIndicatorView = activityIndicatorView;
}
#pragma mark 发送信息

//  结合 聊天和 问答的发送消息
- (void)clickSenBtnToSendMessage {
    
    UITextView *textView = nil;
    UIButton *button = nil;
    
    if (_isLandscapeRight == false) {
        textView = _chatTextView;
        button = _keyboardButton;
    } else {
        textView = _chatLandscapeTextView;
        button = _keyboardLandscapeButton;
    }
    
    [textView resignFirstResponder];
    if (textView.text == nil || [textView.text length] == 0 || [textView.text isEqualToString:kDefaultPlaceHolder]) {
        
        [UIAlertController showAlertViewWithController:self
                                                 title:@"警告"
                                               message:@"发送内容不能为空"
                                     cancelButtonTitle:@"OK"
                                    confirmButtonTitle:nil
                                           cancelBlock:nil
                                          confirmBlock:nil];
    } else {
        
        if (_isLandscapeRight) {
            
            [self chatMessage:textView.text];

        }else if (_selectedIndx == 1){
            
            if (_isPublicChat == true) {
                [self chatMessage:textView.text];
            } else {
                [self privateChat:textView.text];
            }
            
        }else if (_selectedIndx == 2) {
            
            [self question:textView.text];
        }
        
        textView.text = @"";
    }
}


# pragma mark - 手势识别 UIGestureRecognizerDelegate
-(void)handleSingleTap:(UIGestureRecognizer*)gestureRecognizer
{
    if (_isLandscapeRight == true) {
        if (_zoomLandscapeBtn.hidden) {
            if (_templateType != 1) {
                [_chatLandscapeInputBackView setHidden:NO];
            }
            [_zoomLandscapeBtn setHidden:NO];
            _hiddenDelaySeconds = 5;
        } else if(_isSystemBoardShow == NO && _isEmojjBoardShow == NO){
            [_chatLandscapeInputBackView setHidden:YES];
            [_zoomLandscapeBtn setHidden:YES];
            _hiddenDelaySeconds = 0;
        } else {
            [_chatLandscapeTextView resignFirstResponder];
            _hiddenDelaySeconds = 5;
        }
    }else {
        [_chatTextView resignFirstResponder];
    }
}

-(void)tapGesture:(UITapGestureRecognizer *)sender
{
    [self.view endEditing:YES];
}
#pragma mark 键盘通知
- (void)keyboardWillShow:(NSNotification *)notif {

    NSDictionary *keyboardInfo = notif.userInfo;
    NSTimeInterval keyShowDuration = [keyboardInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect keyboardFrame = [keyboardInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardFrame.size.height;

    
    if (_isSystemBoardShow == false) {
        _isSystemBoardShow = true;
        _isEmojjBoardShow = true;
        [_keyboardButton setImage:[UIImage imageNamed:@"board_emoji"] forState:UIControlStateNormal];
        [_keyboardLandscapeButton setImage:[UIImage imageNamed:@"board_emoji"] forState:UIControlStateNormal];
        
        [_chatTextView setInputView:nil];
        [_chatLandscapeTextView setInputView:nil];
    }
    _isSystemBoardShow = true;
    if (_isLandscapeRight == false && CGRectEqualToRect(_chatInputViewSize,CGRectZero)) {
        _chatInputViewSize = keyboardFrame;
    } else if (_isLandscapeRight == true && CGRectEqualToRect(_chatLandscapeInputViewSize,CGRectZero)){
        _chatLandscapeInputViewSize = keyboardFrame;
    }
    
    [UIView animateWithDuration:keyShowDuration animations:^{
        if (_isLandscapeRight == true) {
            _hiddenDelaySeconds = 5;
            _chatLandscapeInputBackView.frame = CGRectMake(0, self.view.frame.size.height - kInputViewH - keyboardHeight - 1, self.view.frame.size.width, kInputViewH);
        } else {
            _chatInputBackView.frame = CGRectMake(0, _height-kInputViewH-keyboardHeight,_width,kInputViewH);
            

        }
    }];
}

- (void)keyboardWillHide:(NSNotification *)notif {
    _isSystemBoardShow = false;
    
    NSDictionary *keyboardInfo = notif.userInfo;
    NSTimeInterval keyShowDuration = [keyboardInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    [UIView animateWithDuration:keyShowDuration animations:^{
        if (_isLandscapeRight == true) {
            _hiddenDelaySeconds = 5;
            _chatLandscapeInputBackView.frame = CGRectMake(0, self.view.frame.size.height - kInputViewH,self.view.frame.size.width,kInputViewH);
            
        } else {
            _chatInputBackView.frame = CGRectMake(0, _height-kInputViewH,_width,kInputViewH);
            
        }
    }];
    
    [self scrollChatTableViewToBottom];
    
}

#pragma mark -- 抽出方法复用
// MARK: 滚动chatTableView到底部

- (void)scrollChatTableViewToBottom {

    if (_selectedIndx == 1 ) {
        
        [_chatTableView reloadData];
        if ([_chatArr count] >= 1) {
            
            NSIndexPath *indexPathLast = [NSIndexPath indexPathForItem:([_chatArr count]-1) inSection:0];
            [_chatTableView scrollToRowAtIndexPath:indexPathLast atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            
        }
        
    }else if(_selectedIndx == 2){
        
        [_chatTableView reloadData];
        if (_QADic != nil && [_QADic count] != 0 ) {
        
            NSInteger count = 0;
            for (NSString *key in _keysArr) {
                NSArray *arr = [_QADic valueForKey:key];
                count += [arr count];
            }
            
            NSIndexPath *indexPathLast = [NSIndexPath indexPathForItem:(count-1) inSection:0];
            [_chatTableView scrollToRowAtIndexPath:indexPathLast atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }

}

#pragma mark scrollView Delegate

//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
//{
//    [self.view endEditing:YES];
//}


#pragma mark -- textView代理方法
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    if ([textView.text isEqualToString:kDefaultPlaceHolder]) {
        
        textView.text = @"";
        [textView setTextColor:[UIColor blackColor]];
        
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    
    NSString *text = [textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    if (text.length == 0) {
        textView.text = kDefaultPlaceHolder;
        [textView setTextColor:HEXCOLOR(0xcecece)];
    }
    
    return YES;
}

//- (void)textViewDidEndEditing:(UITextView *)textView {
//    textView.text = kDefaultPlaceHolder;
//    [textView setTextColor:HEXCOLOR(0xcecece)];
//
//}

#pragma mark tableView 数据源/代理

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_selectedIndx == 1) {
        return _chatArr.count;
    } else if(_selectedIndx == 2){
        NSInteger count = 0;
        for (NSString *key in _keysArr) {
            NSArray *arr = [_QADic valueForKey:key];
            count += [arr count];
        }
        return count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_selectedIndx == 1) {
        
        if (indexPath.row < [_chatArr count]) {
            Dialog *dialog = [_chatArr objectAtIndex:indexPath.row];
            return [BIZLiveRoomTableViewCellNew heightOfCellWithMessage:dialog.content title:dialog.username];
        } else {
            return 44;
        }
    }else if(_selectedIndx == 2){
        
        NSInteger count = 0;
        for (NSString *key in _keysArr) {
            NSArray *arr = [_QADic valueForKey:key];
            count += [arr count];
        }
        if (indexPath.row < count) {
            count = indexPath.row;
            NSInteger count1 = 0;
            NSInteger count2 = count - count1;
            
            for (NSString *key in _keysArr) {
                NSArray *arr = [_QADic valueForKey:key];
                NSInteger count3 = [arr count];
                if (count2 >= count3) {
                    count1 += count3;
                    count2 = count - count1;
                } else {
                    Dialog *dialog = [arr objectAtIndex:count2];
                    return [BIZLiveRoomTableViewCellNew heightOfCellWithMessage:dialog.content title:[dialog.username stringByAppendingString:@"(问)"]];
                }
            }
        } else {
            return 44;
        }
    }else {
        return 44;
    }
    return 44;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    BIZLiveRoomTableViewCellNew *cell = [BIZLiveRoomTableViewCellNew cellWithTableView:tableView];
    
    Dialog *dialog = nil;
    BIZLiveRoomTableViewCellNewSpokesmanType type = BIZLiveRoomTableViewCellNewSpokesmanTypeSelf;

    if (_selectedIndx == 1) {
        dialog = [_chatArr objectAtIndex:indexPath.row];
        
        if ([dialog.viewerId isEqualToString:self.viewerId]) {// 自己

            if (dialog.isPublicChat == false) {// 私聊
                [cell showMessage:dialog.content spokesmanType:type title:[dialog.username stringByAppendingString:@"(私聊)"]];
                
            } else {// 公聊
                [cell showMessage:dialog.content spokesmanType:type title:dialog.username];

            }
        } else {// 非本人
            
            type = [dialog.userRole isEqualToString:@"publisher"] ?BIZLiveRoomTableViewCellNewSpokesmanTypePublisher:BIZLiveRoomTableViewCellNewSpokesmanTypeOthers;

            if (dialog.isPublicChat == false) {
                [cell showMessage:dialog.content spokesmanType:type title:[dialog.username stringByAppendingString:@"(教师私聊自己)"]];
                
            } else {
                
                [cell showMessage:dialog.content spokesmanType:type title:dialog.username];
        
            }
        }
    } else if(_selectedIndx == 2){
        NSInteger count = indexPath.row;
        NSInteger count1 = 0;
        NSInteger count2 = count - count1;
        for (NSString *key in _keysArr) {
            NSArray *arr = [_QADic valueForKey:key];
            NSInteger count3 = [arr count];
            if (count2 >= count3) {
                count1 += count3;
                count2 = count - count1;
            } else {
                Dialog *dialog = [arr objectAtIndex:count2];
                if (dialog.dataType == NS_CONTENT_TYPE_QA_QUESTION) {
                    if ([dialog.viewerId isEqualToString:self.viewerId]) {
                        [cell showMessage:dialog.content spokesmanType:type title:[dialog.username stringByAppendingString:@"(问)"]];
                        
                    } else {
                        type = [dialog.userRole isEqualToString:@"publisher"] ?BIZLiveRoomTableViewCellNewSpokesmanTypePublisher:BIZLiveRoomTableViewCellNewSpokesmanTypeOthers;

                        [cell showMessage:dialog.content spokesmanType:type title:[dialog.username stringByAppendingString:@"(问)"]];

                    }
                } else if (dialog.dataType == NS_CONTENT_TYPE_QA_ANSWER) {
                    
                    type = [dialog.userRole isEqualToString:@"publisher"] ?BIZLiveRoomTableViewCellNewSpokesmanTypePublisher:BIZLiveRoomTableViewCellNewSpokesmanTypeOthers;

                    [cell showMessage:dialog.content spokesmanType:type title:[dialog.username stringByAppendingString:@"(答)"]];
                    
                }
                break;
            }
        }
    }
    return cell;
}


- (void)firRoad:(NSInteger)firRoadNum secRoadKeyArray:(NSArray *)secRoadKeyArray {
    [self createMenuWithFirRoad:firRoadNum secRoadKeyArray:secRoadKeyArray];
}

#pragma mark 切换线路
- (void)createMenuWithFirRoad:(NSInteger)firRoadNum secRoadKeyArray:(NSArray *)secRoadKeyArray {
    [_secRoadKeyArray removeAllObjects];
    _secRoadKeyArray = [[NSMutableArray alloc] initWithArray:secRoadKeyArray];
    [_firstArr removeAllObjects];
    _firstArr = [[NSMutableArray alloc] init];
    [_secArr removeAllObjects];
    _secArr = [[NSMutableArray alloc] init];
    
    //    NSLog(@"firRoadNum = %d,secRoadKeyArray = %@",firRoadNum,secRoadKeyArray);
    
    // Do any additional setup after loading the view, typically from a nib.
//    [_activityBtn removeFromSuperview];
//    _activityBtn = nil;
//    _activityBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
//    _activityBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
//    NSString *title = @"源1(声音图像原画)";
//    [_activityBtn setTitle:title forState:UIControlStateNormal];
//    [_activityBtn setTitleColor:[UIColor whiteColor]  forState:UIControlStateNormal];
//    NSDictionary *dict = @{NSFontAttributeName:_activityBtn.titleLabel.font};
//    CGSize size = [title boundingRectWithSize:CGSizeMake(150, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
//    _activityBtn.frame = CGRectMake(_activityBtn.frame.origin.x, _activityBtn.frame.origin.y,size.width+33, 30);
//    _activityBtn.imageEdgeInsets = UIEdgeInsetsMake(11, size.width+23, 11, 0);
//    [_activityBtn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_activityBtn];
    
    for(int i = 0; i < firRoadNum ;i++ ) {
        NSString *str = [NSString stringWithFormat:@"源%d",i+1];
        [_firstArr addObject:str];
        NSMutableArray *array = [[NSMutableArray alloc]init];
        for(int j = 0;j < [secRoadKeyArray count]; j++) {
            NSString *title = [NSString stringWithFormat:@"%@(声音图像%@)",str,[secRoadKeyArray objectAtIndex:j]];
            [array addObject:title];
        }
        [array addObject:[NSString stringWithFormat:@"%@(只听声音)",str]];
        [_secArr addObject:array];
    }
    _currentArr = _secArr[0];
    
    [_menu removeFromSuperview];
    _menu = nil;
    _menu = [[FSDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:152];
    _menu.transformView = _activityBtn.imageView;
    _menu.tag = 1001;
    _menu.dataSource = self;
    _menu.delegate = self;
    if(_isLandscapeRight == true) {
        _menu.hidden = YES;
    }
    [self.view addSubview:_menu];
}

-(void)btnPressed:(id)sender{
    if(_status != 0) return;
    FSDropDownMenu *menu = (FSDropDownMenu*)[self.view viewWithTag:1001];
    [UIView animateWithDuration:0.2 animations:^{
        
    } completion:^(BOOL finished) {
        [menu menuTapped];
    }];
}
/**
 *	@brief   切换播放线路
 *  firIndex表示第几个源
 *  key表示该源对应的描述信息
 */
-(void)resetButtonTitle:(NSString*)str firIndex:(NSInteger)firIndex key:(NSString *)key {
    //NSLog(@"str = %@",str);
    UIButton *btn = (UIButton*)self.navigationItem.rightBarButtonItem.customView;
    [btn setTitle:str forState:UIControlStateNormal];
    NSDictionary *dict = @{NSFontAttributeName:btn.titleLabel.font};
    CGSize size = [str boundingRectWithSize:CGSizeMake(150, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    btn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y,size.width+33, 30);
    btn.imageEdgeInsets = UIEdgeInsetsMake(11, size.width+23, 11, 0);
    
    [_requestData switchToPlayUrlWithFirIndex:firIndex key:key];
}

- (NSInteger)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == menu.rightTableView) {
        return _firstArr.count;
    }else{
        return _currentArr.count;
    }
}

- (NSString *)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView titleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == menu.rightTableView) {
        return _firstArr[indexPath.row];
    }else{
        return _currentArr[indexPath.row];
    }
}

- (void)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView == menu.rightTableView){
        _currentArr = _secArr[indexPath.row];
        _indexPre = indexPath.row;
        [menu.leftTableView reloadData];
    }else{
        if(indexPath.row + 1 == [_currentArr count]) {
            [self resetButtonTitle:_currentArr[indexPath.row] firIndex:_indexPre key:@""];
        } else {
            [self resetButtonTitle:_currentArr[indexPath.row] firIndex:_indexPre key:_secRoadKeyArray[indexPath.row]];
        }
        _indexPre = 0;
    }
}

- (void)moviePlayBackStateDidChange:(NSNotification*)notification
{
    switch (_requestData.playState)
    {
        case MoviePlayStateStopped: {
            [self startAnimating];
            break;
        }
        case MoviePlayStatePlaying: {
            [_activityIndicatorView stopAnimating];
            [_videoParent bringSubviewToFront:_overlayView];
            break;
        }
        case MoviePlayStatePaused: {
            [_activityIndicatorView stopAnimating];
            break;
        }
        case MoviePlayStateInterrupted: {
            [self startAnimating];
            break;
        }
        case MoviePlayStateSeekingForward:
        case MoviePlayStateSeekingBackward: {
            [self startAnimating];
            break;
        }
        default: {
            break;
        }
    }
}

- (void)isPreparingToPlayNoti:(NSNotification*)notification
{
    [self startAnimating];
    _informationLabel.hidden = YES;
}

- (void)movieLoadStateDidChange:(NSNotification *)notification {
    switch (_requestData.loadState) {
        case MovieLoadStateUnknown: {
            //            [self changeIntoLiveFromBackView];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark Requestdata delegate 自动回调
/**
 *	@brief  收到提问&回答
 */
- (void)onQuestionArr:(NSArray *)questionArr onAnswerArr:(NSArray *)answerArr
{
        NSLog(@"questionArr = %@,answerArr = %@",questionArr,answerArr);
    
    if ([questionArr count] == 0 && [answerArr count] == 0) {
        return;
    }
    
    [_QADic removeAllObjects];
    [_keysArr removeAllObjects];
    
    for (NSDictionary *dic in questionArr) {
        Dialog *dialog = [[Dialog alloc] init];
        dialog.content = dic[@"content"];
        dialog.username = dic[@"questionUserName"];
        dialog.viewerId = dic[@"questionUserId"];
        dialog.encryptId = dic[@"encryptId"];
        dialog.avatar = dic[@"useravatar"];
        dialog.dataType = NS_CONTENT_TYPE_QA_QUESTION;
        dialog.userRole = dic[@"userRole"];
        NSMutableArray *arr = [_QADic objectForKey:dialog.encryptId];
        if (arr == nil) {
            arr = [[NSMutableArray alloc] init];
            [_QADic setObject:arr forKey:dialog.encryptId];
            [_keysArr addObject:dialog.encryptId];
        }
        [arr addObject:dialog];
    }
    
    for (NSDictionary *dic in answerArr) {
        Dialog *dialog = [[Dialog alloc] init];
        dialog.content = dic[@"content"];
        dialog.username = dic[@"answerUserName"];
        dialog.viewerId = dic[@"answerUserId"];
        dialog.encryptId = dic[@"encryptId"];
        dialog.avatar = dic[@"useravatar"];
        dialog.dataType = NS_CONTENT_TYPE_QA_ANSWER;
        dialog.userRole = dic[@"userRole"];

        BOOL isPrivate = [dic[@"isPrivate"] boolValue];
        if (isPrivate == 0) {
            NSMutableArray *arr = [_QADic objectForKey:dialog.encryptId];
            if (arr != nil) {
                [arr addObject:dialog];
            }
        }
    }
    [self scrollChatTableViewToBottom];
}

/**
 *	@brief  收到提问
 */
- (void)onQuestionDic:(NSDictionary *)questionDic
{
    NSLog(@"收到提问: questionDic = %@",questionDic);
    if ([questionDic count] == 0) questionDic = nil ;
    
    if (questionDic) {
        Dialog *dialog = [[Dialog alloc] init];
        dialog.content = questionDic[@"value"][@"content"];
        dialog.username = questionDic[@"value"][@"userName"];
        dialog.viewerId = questionDic[@"value"][@"userId"];
        dialog.encryptId = questionDic[@"value"][@"id"];
//        dialog.userRole = questionDic[@"value"][@"userRole"];
        dialog.avatar = questionDic[@"useravatar"];
        dialog.dataType = NS_CONTENT_TYPE_QA_QUESTION;
        NSMutableArray *arr = [_QADic objectForKey:dialog.encryptId];
        if (arr == nil) {
            arr = [[NSMutableArray alloc] init];
            [_QADic setObject:arr forKey:dialog.encryptId];
            [_keysArr addObject:dialog.encryptId];
        }
        [arr addObject:dialog];
        
        [self scrollChatTableViewToBottom];
    }
}
/**
 *	@brief  收到回答
 */
- (void)onAnswerDic:(NSDictionary *)answerDic
{
    NSLog(@"收到回答: answerDic = %@",answerDic);
    if ([answerDic count] == 0) answerDic = nil ;
    
    if (answerDic) {
        Dialog *dialog = [[Dialog alloc] init];
        dialog.content = answerDic[@"value"][@"content"];
        dialog.username = answerDic[@"value"][@"userName"];
        dialog.userRole = answerDic[@"value"][@"userRole"];
        dialog.viewerId = answerDic[@"value"][@"userId"];
        dialog.encryptId = answerDic[@"value"][@"questionId"];
        dialog.avatar = answerDic[@"useravatar"];
        dialog.dataType = NS_CONTENT_TYPE_QA_ANSWER;
        BOOL isPrivate = [answerDic[@"value"][@"isPrivate"] boolValue];
        NSString *questionUserId = answerDic[@"value"][@"questionUserId"];
        if (isPrivate == 0 || (isPrivate == 1 && [questionUserId isEqualToString:self.viewerId])) {
            NSMutableArray *arr = [_QADic objectForKey:dialog.encryptId];
            if (arr == nil) {
                arr = [[NSMutableArray alloc] init];
                [_QADic setObject:arr forKey:dialog.encryptId];
            }
            [arr addObject:dialog];
            
            [self scrollChatTableViewToBottom];
        }
    }
}
/**
 *	@brief  收到公聊
 */
- (void)onPublicChatMessage:(NSDictionary *)message
{
    //NSLog(@"收到公聊 = %@", message);
    if (message == nil || [message count] == 0) return ;
    Dialog *dialog = [[Dialog alloc] init];
    dialog.isPublicChat = true;
    dialog.content = message[@"msg"];
    dialog.username = message[@"username"];
    dialog.viewerId = message[@"userid"];
    dialog.avatar = message[@"useravatar"];
    dialog.dataType = NS_CONTENT_TYPE_CHAT;
    dialog.userRole = message[@"userrole"];
    
    [_chatArr addObject:dialog];
    [self insertStr:dialog.content];
    [self scrollChatTableViewToBottom];
    
}

/*
 *  @brief  收到用户禁言消息
 */
- (void)onSilenceUserChatMessage:(NSDictionary *)message
{
    //    {"userid":"c76ae2921a1448ec92ee8ee67862c50f","username":"test123","msg":"高年级","time":"18:21:09"}
    //服务端返回的禁言信息里面只有userid，username，msg，time四个信息，并不知道是公聊还是私聊信息，所以暂时只按照公聊来现实信息，以后有需要再改正
    //NSLog(@"收到用户禁言消息 = %@", message);
    if (message == nil || [message count] == 0) return ;
    Dialog *dialog = [[Dialog alloc] init];
    dialog.isPublicChat = true;
    dialog.content = message[@"msg"];
    dialog.username = message[@"username"];
    dialog.viewerId = message[@"userid"];
    dialog.avatar = message[@"useravatar"];
    dialog.dataType = NS_CONTENT_TYPE_CHAT;
    [_chatArr addObject:dialog];
    [self insertStr:dialog.content];
    [self scrollChatTableViewToBottom];

}
/**
 *	@brief  收到私聊消息
 */
- (void)OnPrivateChat:(NSDictionary *)message
{
    //NSLog(@"收到私聊消息 = %@", message);
    if (message == nil || [message count] == 0) return ;
    Dialog *dialog = [[Dialog alloc] init];
    dialog.isPublicChat = false;
    dialog.content = message[@"msg"];
    dialog.username = message[@"fromusername"];
    dialog.viewerId = message[@"fromuserid"];
    dialog.avatar = message[@"useravatar"];
    dialog.dataType = NS_CONTENT_TYPE_CHAT;
    [_chatArr addObject:dialog];
    [self insertStr:dialog.content];
    [self scrollChatTableViewToBottom];
}
/**
 *	@brief  收到学生私聊
 */
- (void)onPrivateMessage:(NSDictionary *)message
{
    //NSLog(@"收到学生私聊 = %@", message);
    if (message == nil || [message count] == 0) return ;
    Dialog *dialog = [[Dialog alloc] init];
    dialog.isPublicChat = false;
    dialog.content = message[@"msg"];
    dialog.username = message[@"username"];
    dialog.viewerId = message[@"userid"];
    dialog.avatar = message[@"useravatar"];
    dialog.dataType = NS_CONTENT_TYPE_CHAT;
    [_chatArr addObject:dialog];
    [self insertStr:dialog.content];
    [self scrollChatTableViewToBottom];
}
/**
 *	@brief	收到禁言信息
 */
- (void)information:(NSString *)information
{
    UITextView *textView = nil;
    if (_isLandscapeRight == false) {
        textView = _chatTextView;
    } else {
        textView = _chatLandscapeTextView;
    }
    [textView resignFirstResponder];
    //NSLog(@"收到禁言信息 = %@", information);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"禁言" message:information delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
/**
 *	@brief	请求成功
 */
-(void)requestSucceed {
    //NSLog(@"请求成功！");
    [self stopRoomContextTimer];
    
    _roomContextTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(func) userInfo:nil repeats:YES];
}

-(void)func {
    [_requestData roomUserCount];
    //    [_requestData roomContext];
}

/**
 *	@brief	请求失败
 */
-(void)requestFailed:(NSError *)error reason:(NSString *)reason {
    //    if(reason != nil) {
    //        //错误信息 = reason;
    //    } else {
    //        //错误信息 = [error localizedDescription];
    //    }
    //NSLog(@"请求错误：%@",[error localizedDescription]);
    if (error.code != ERROR_ROOM_STATE) {
        //        [self exitMessage];
    } else {
        _informationLabel.text = @"直播未开始";
        [_informationLabel setHidden:NO];
        [_activityIndicatorView stopAnimating];
    }
}

/**
 *	@brief  主讲开始推流
 */
- (void)onLiveStatusChangeStart{
    //NSLog(@"主讲开始推流");
    [self startAnimating];
    [_informationLabel setHidden:YES];
}

-(void)stopRoomContextTimer {
    if([_roomContextTimer isValid]) {
        [_roomContextTimer invalidate];
        _roomContextTimer = nil;
    }
}
/**
 *	@brief  主讲停止推流
 */
- (void)onLiveStatusChangeEnd:(BOOL)endNormal{
    //NSLog(@"主讲停止推流------%d",endNormal);
    _status = 1;
    _informationLabel.text = @"直播已停止";
    [_informationLabel setHidden:NO];
    [_activityIndicatorView stopAnimating];
    [_requestData shutdownPlayer];
    
}

/**
 *	@brief  收到退出消息，停止直播并退出播放
 */
- (void)onKickOut
{
    //NSLog(@"停止直播，播放器停止播放");
    [_requestData stopPlayer];
    [self exitMessage];
    [self.view endEditing:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"您已被管理员踢出！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *	@brief  收到播放直播状态 0直播 1未直播
 */
- (void)getPlayStatue:(LIVEPREPAREPLAYER)status {
    _status = status;
}
/**
 *	@brief	收到在线人数
 */
- (void)onUserCount:(NSString *)count
{
    //    NSLog(@"收到在线人数 = %@", count);
}
/**
 *	@brief	设置UserId
 */
-(void)setMyViewerId:(NSString *)viewerId
{
    //NSLog(@"viewerId = %@",viewerId);
    self.viewerId = viewerId;
}
#pragma mark 用户主动行为
/**
 *	@brief  发送提问
 */
- (void)question:(NSString *)message {
    //    NSString *message = @"发送提问";
    [_requestData question:message];
}
/**
 *	@brief  发送公聊信息
 */
- (void)chatMessage:(NSString *)message {
    //    NSString *message = @"发送公聊信息";
    [_requestData chatMessage:message];
}
/**
 *	@brief  发送私聊信息
 */
- (void)privateChat:(NSString *)message {
    //    [_requestData privateChat:message];
}
/**
 *	@brief  询问在线人数
 */
- (void)roomUserCount {
    [_requestData roomUserCount];
}
/**
 *	@brief  销毁文档和视频
 */
- (void)exitMessage {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:CCMovieIsPreparingToPlayNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:CCMoviePlayStateChangedNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:CCMovieLoadStateChangedNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification  object:nil];
    [self stopConnectTimer];
    
    [self stopRoomContextTimer];
    
    [_requestData requestCancel];
    
    _requestData = nil;
}

-(CGSize)getTitleSizeByFont:(NSString *)str width:(CGFloat)width font:(UIFont *)font{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, 20000.0f) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return size;
}

- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf withPositon:(int)position
{
    UIFont *font = [UIFont systemFontOfSize:18];
    
    CGSize size = [self getTitleSizeByFont:text width:180.0f font:font];
    
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    returnView.backgroundColor = [UIColor clearColor];
    
    UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"SenderAppNodeBkg_HL":@"ReceiverTextNodeBkg" ofType:@"png"]];
    UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:floorf(bubble.size.width / 2) topCapHeight:floorf(bubble.size.height / 2)]];
    //NSLog(@"%f,%f",size.width,size.height);
    
    UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(fromSelf?15.0f:22.0f, 20.0f, size.width + 10, size.height + 10)];
    bubbleText.backgroundColor = [UIColor clearColor];
    bubbleText.font = font;
    bubbleText.numberOfLines = 0;
    bubbleText.lineBreakMode = NSLineBreakByWordWrapping;
    bubbleText.text = text;
    
    bubbleImageView.frame = CGRectMake(0.0f, 14.0f, bubbleText.frame.size.width + 30.0f, bubbleText.frame.size.height + 20.0f);
    if(fromSelf)
        returnView.frame = CGRectMake(self.view.frame.size.width - position - (bubbleText.frame.size.width + 30.0f), 18.0f, bubbleText.frame.size.width + 30, bubbleText.frame.size.height + 30);
    else
        returnView.frame = CGRectMake(position, 18.0f, bubbleText.frame.size.width + 30.0f, bubbleText.frame.size.width + 30.0f);
    
    [returnView addSubview:bubbleImageView];
    [returnView addSubview:bubbleText];
    
    return returnView;
}

- (void) startTimer {
    [self stopTimer];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(makeTheRightAction) userInfo:nil repeats:YES];
}

- (void) stopTimer {
    if ([_timer isValid]){
        [_timer invalidate];
        _timer=nil;
        [_array removeAllObjects];
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
    }
}
- (void)makeTheRightAction {
    //    //NSLog(@"%s",__FUNCTION__);
    if (!_zoomLandscapeBtn.hidden && (_isSystemBoardShow == NO && _isEmojjBoardShow == NO)) {
        if (_hiddenDelaySeconds > 0) {
            if (_hiddenDelaySeconds == 1) {
                [_chatLandscapeInputBackView setHidden:YES];
                [_zoomLandscapeBtn setHidden:YES];
            }
            _hiddenDelaySeconds--;
        }
    }
    
    for(int i = 0;i < _lineLimit;i++){
        if ([_array count] >= 1) {
            [self makeLabel:[_array objectAtIndex:0] currentLine:i];
            [_array removeObjectAtIndex:0];
        } else {
            break;
        }
    }
}

- (void)insertStr:(NSString *)str{
    if (_timer) {
        [_array addObject:str];
    }
}

- (void)makeLabel:(NSString *)str currentLine:(int)currentLine{
    if (_isLandscapeRight == false) {
        return;
    }
    
    NSMutableAttributedString *attrStr = [Utility emotionStrWithString:str y:-8];
    [attrStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:20.0f]
                    range:NSMakeRange(0, attrStr.length)];
    CGSize textSize = [attrStr boundingRectWithSize:CGSizeMake(100000, CGFLOAT_MAX)
                                            options:NSStringDrawingUsesLineFragmentOrigin
                                            context:nil].size;
    
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width, IMGWIDTH * 0.5 * (currentLine + 1) + IMGWIDTH * currentLine, textSize.width, textSize.height)];
    contentLabel.font = [UIFont systemFontOfSize:20.0f];
    contentLabel.numberOfLines = 1;
    contentLabel.attributedText = attrStr;
    contentLabel.backgroundColor = [UIColor clearColor];
    //设置字体颜色为green
    contentLabel.textColor = [UIColor greenColor];
    //文字居中显示
    contentLabel.textAlignment = NSTextAlignmentCenter;
    //自动折行设置
    contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
    
    [_overlayView addSubview:contentLabel];
    
    [self moveAction:contentLabel size:textSize];
}

- (void)moveAction:(UIView *)view size:(CGSize) size {
    [UIView animateWithDuration:_secondToEnd delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{
        view.frame = CGRectMake(-size.width,view.frame.origin.y,size.width,size.height);
    } completion:^(BOOL finished) {
        [view removeFromSuperview];
    }];
}

# pragma mark - 手势识别 UIGestureRecognizerDelegate
-(void)handleDoubleTap
{
    //NSLog(@"接收到手势信号");
    //TODO
    if (_activityIndicatorView.isAnimating) {
        return;
    }
    [self.view endEditing:YES];
    if (_isLandscapeRight == false) {
        //  如果当前是设备是物理竖屏,先回复横屏,保证后面有转屏动画
        if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft) {
            [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
        }

        _isLandscapeRight = true;
        // 5 秒后隐藏所有窗口
        _hiddenDelaySeconds = 5;
        //NSLog(@"竖屏转横屏");
        _menu.hidden = YES;
        _allowRotate = YES;
        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:YES];

        [[UIApplication sharedApplication] setStatusBarHidden:YES];

        [self.view bringSubviewToFront:_bgview];
//        self.navigationController.navigationBarHidden = YES;
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
        [_requestData setPlayerFrame:self.view.frame];
        CGRect videoRect = CGRectMake(0, CGRectGetHeight(self.view.frame) / 3, CGRectGetHeight(self.view.frame) * (2 * 4) / (3 * 3), CGRectGetHeight(self.view.frame) * 2 / 3);
        [_requestData setLocalVideoFrameA:videoRect];
        if(_videosizeStr) {
            [_requestData setRemoteVideoFrameA:[self calculateRemoteVIdeoRect:self.view.frame]];
        } else {
            [_requestData setRemoteVideoFrameA:self.view.frame];
        }
        
        if([_information.text isEqualToString:@"申请中"]) {
            self.information.frame = CGRectMake(0, 0,videoRect.size.width, videoRect.size.height / 7);
        }
        _bgview.frame = self.view.frame;
        _overlayView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        _activityIndicatorView.center = CGPointMake(CGRectGetMidX(_overlayView.frame), CGRectGetMidY(_overlayView.frame));
        _informationLabel.center = CGPointMake(CGRectGetMidX(_bgview.bounds), CGRectGetMidY(_bgview.bounds));
        
        _chatLandscapeInputBackView.frame = CGRectMake(0, self.view.frame.size.height - kInputViewH,self.view.frame.size.width,kInputViewH);

        _chatLandscapeTextView.text = _chatTextView.text;
    
        if (_templateType != 1) {
            [_chatLandscapeInputBackView setHidden:NO];
        }
        [_zoomLandscapeBtn setHidden:NO];
        _zoomLandscapeBtn.frame = CGRectMake(5,5,50,50);
        [_zoomBtn setHidden:YES];
        [self startTimer];
    } else {
        
        //  如果当前是设备是物理竖屏,先回复横屏,保证后面有转屏动画
        if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {
            [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
        }

        _isLandscapeRight = false;
        //NSLog(@"横屏转竖屏");
        _hiddenDelaySeconds = 0;
        _menu.hidden = NO;
        _allowRotate = YES;

        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
//        self.navigationController.navigationBarHidden = NO;
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:YES];

        self.view.transform = CGAffineTransformMakeRotation(0);
        [self.view sendSubviewToBack:_bgview];
        CGRect playerFrame = CGRectMake(0, 0, _videoFrame.size.width, _videoFrame.size.height);
        [_requestData setPlayerFrame:playerFrame];
        CGRect videoRect = CGRectMake(0, CGRectGetHeight(playerFrame) / 3, CGRectGetHeight(playerFrame) * (2 * 3) / (3 * 4), CGRectGetHeight(playerFrame) * 2 / 3);
        [_requestData setLocalVideoFrameA:videoRect];
        
        if(_videosizeStr) {
            [_requestData setRemoteVideoFrameA:[self calculateRemoteVIdeoRect:self.videoFrame]];
        } else {
            [_requestData setRemoteVideoFrameA:playerFrame];
        }
        
        if([_information.text isEqualToString:@"申请中"]) {
            self.information.frame = CGRectMake(0, 0,videoRect.size.width, videoRect.size.height / 7);
        }
        _bgview.frame = _videoFrame;
        _overlayView.frame = CGRectMake(0, 0, _bgview.frame.size.width, _bgview.frame.size.height);
        _activityIndicatorView.center = CGPointMake(CGRectGetMidX(_overlayView.frame), CGRectGetMidY(_overlayView.frame));
        _informationLabel.center = CGPointMake(CGRectGetMidX(_bgview.bounds), CGRectGetMidY(_bgview.bounds));
        [_zoomBtn setHidden:NO];
        _zoomBtn.frame = CGRectMake(_overlayView.frame.size.width - 37,_overlayView.frame.size.height - 35,30,30);
        _chatTextView.text = _chatLandscapeTextView.text;
        [_chatLandscapeInputBackView setHidden:YES];
        [_zoomLandscapeBtn setHidden:YES];

        [self stopTimer];
        [_chatTableView reloadData];
        [self scrollChatTableViewToBottom];
    }
}

- (UIView *)createEmojjViewWithFrame:(CGRect)frame {
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:236.0/255.0 blue:236.0/255.0 alpha:1];
    
    CGFloat xspace = (frame.size.width - FACE_COUNT_CLU * FACE_ICON_SIZE) / (FACE_COUNT_CLU + 1);
    CGFloat yspace = (frame.size.height - 26 - FACE_COUNT_ROW * FACE_ICON_SIZE) / (FACE_COUNT_ROW + 1);
    
    for (int i = 0; i < FACE_COUNT_ALL; i++) {
        UIButton *faceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        faceButton.tag = i + 1;
        
        [faceButton addTarget:self action:@selector(faceButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        //计算每一个表情按钮的坐标和在哪一屏
        CGFloat x = (i % FACE_COUNT_CLU + 1) * xspace + (i % FACE_COUNT_CLU) * FACE_ICON_SIZE;
        CGFloat y = (i / FACE_COUNT_CLU + 1) * yspace + (i / FACE_COUNT_CLU) * FACE_ICON_SIZE;
        
        faceButton.frame = CGRectMake(x, y, FACE_ICON_SIZE, FACE_ICON_SIZE);
        [faceButton setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%02d", i+1]]
                    forState:UIControlStateNormal];
        
        [view addSubview:faceButton];
    }
    
    //添加PageControl
    UIPageControl *facePageControl = [[UIPageControl alloc]initWithFrame:CGRectMake((frame.size.width - 100) / 2, frame.size.height - 26, 100, 20)];
    [facePageControl addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged];
    facePageControl.numberOfPages = 1;
    facePageControl.currentPage = 0;
    [view addSubview:facePageControl];
    
    UIImageView* dot = [view.subviews objectAtIndex:0];
    if ([dot isKindOfClass:UIImageView.class] ) {
        ((UIImageView *) dot).image = [UIImage imageNamed:@"inactive_page_image"];;
    }
    
    //删除键
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setImage:[UIImage imageNamed:@"del_emoji_normal"] forState:UIControlStateNormal];
    [back setImage:[UIImage imageNamed:@"del_emoji_select"] forState:UIControlStateSelected];
    [back addTarget:self action:@selector(backFace) forControlEvents:UIControlEventTouchUpInside];
    back.frame = CGRectMake(frame.size.width - 60, frame.size.height - 34, 50, 28);
    [view addSubview:back];
    return view;
}

- (void)pageChange:(id)sender {
    
}

- (void)faceButtonClicked:(id)sender {
    NSInteger i = ((UIButton*)sender).tag;
    UITextView *textView = nil;
    if (_isLandscapeRight == false) {
        textView = _chatTextView;
    } else {
        textView = _chatLandscapeTextView;
    }
    
    NSMutableString *faceString = [[NSMutableString alloc]initWithString:textView.text];
    [faceString appendString:[NSString stringWithFormat:@"[em2_%02d]",(int)i]];
    textView.text = faceString;
}

- (void) backFace {
    UITextView *textView = nil;
    if (_isLandscapeRight == false) {
        textView = _chatTextView;
    } else {
        textView = _chatLandscapeTextView;
    }
    
    NSString *inputString = textView.text;
    if ( [inputString length] > 0) {
        NSString *string = nil;
        NSInteger stringLength = [inputString length];
        if (stringLength >= FACE_NAME_LEN) {
            string = [inputString substringFromIndex:stringLength - FACE_NAME_LEN];
            NSRange range = [string rangeOfString:FACE_NAME_HEAD];
            if ( range.location == 0 ) {
                string = [inputString substringToIndex:[inputString rangeOfString:FACE_NAME_HEAD options:NSBackwardsSearch].location];
            }
            else {
                string = [inputString substringToIndex:stringLength - 1];
            }
        }
        else {
            string = [inputString substringToIndex:stringLength - 1];
        }
        if ( textView ) {
            textView.text = string;
        }
    }
}

/**
 *	@brief  获取文档内白板或者文档本身的宽高
 */
- (void)getDocAspectRatioOfWidth:(CGFloat)width height:(CGFloat)height{
    //NSLog(@"width = %f,height = %f,playLiveUtil = %f",width,height,[_playLiveUtil getDocAspectRatio]);
}

-(void) videoLoadFail{
    _informationLabel.text = @"视频加载失败";
    [_informationLabel setHidden:NO];
    [_activityIndicatorView stopAnimating];
}
/**
 *	@brief  房间信息
 */
-(void)roomInfo:(NSDictionary *)dic{
    _templateType = [dic[@"templateType"] integerValue];
    
    if (_templateType == 1) {
        //聊天互动： 无 直播文档： 无 直播问答： 无
        [_switchView setHidden:YES];
        [_scrollView setHidden:YES];
    } else if (_templateType == 2) {
        //聊天互动： 有 直播文档： 无 直播问答： 有
    
        _selectedIndx = 1;
    } else if (_templateType == 3) {
        //聊天互动： 有 直播文档： 无 直播问答： 无
        _selectedIndx = 1;
    } else if (_templateType == 4) {
        //聊天互动： 有 直播文档： 有 直播问答： 无
        
    } else if (_templateType == 5) {
        //聊天互动： 有 直播文档： 有 直播问答： 有
    }else if(_templateType == 6) {
        //聊天互动： 无 直播文档： 无 直播问答： 有
    }
}

- (void)connectWebRTCSuccess {
    _activityBtn.hidden = YES;
    _informationLabel.hidden = YES;
    [_activityIndicatorView stopAnimating];
    
    self.currenttime = [[NSDate date] timeIntervalSince1970];
    self.information.text = @"连麦中 00:00";
    [self.information removeFromSuperview];
    CGRect viewRect = self.remoteView.frame;
    CGRect videoRect = CGRectMake(0, CGRectGetHeight(viewRect) * 5 / 7, CGRectGetWidth(viewRect) / 2, CGRectGetHeight(viewRect) / 7);
    [self.information setFrame:videoRect];
    [self.remoteView addSubview:self.information];
    
    [self stopConnectTimer];
    _connectTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timefunc) userInfo:nil repeats:YES];
}

-(void)stopConnectTimer {
    if([_connectTimer isValid]) {
        [_connectTimer invalidate];
    }
    _connectTimer = nil;
}

-(void)timefunc {
    NSInteger value = [[NSDate date] timeIntervalSince1970] - self.currenttime;
    NSInteger minutes = value / 60;
    NSInteger seconds = value % 60;
    self.information.text = [NSString stringWithFormat:@"连麦中 %02ld:%02ld",(long)minutes,(long)seconds];
}

- (void)acceptSpeak:(NSDictionary *)dict {
    _lianmaiAVBtn.hidden = YES;
    _lianmaiLabel.hidden = YES;
    _disconnectLianmaiBtn.hidden = NO;
    [_disconnectLianmaiBtn setTitle:@"挂断视频连麦" forState:UIControlStateNormal];
    _videosizeStr = dict[@"videosize"];
    CGRect rect = CGRectZero;
    if(_isLandscapeRight == false) {
        rect = self.videoFrame;
    } else {
        rect = self.view.frame;
    }
    
    self.remoteView.frame = [self calculateRemoteVIdeoRect:rect];
    
    [_requestData saveUserInfo:dict remoteView:self.remoteView];
}

-(CGRect) calculateRemoteVIdeoRect:(CGRect)rect {
    //字符串是否包含有某字符串
    NSRange range = [_videosizeStr rangeOfString:@"x"];
    float remoteSizeWHPercent = [[_videosizeStr substringToIndex:range.location] floatValue] / [[_videosizeStr substringFromIndex:(range.location + 1)] floatValue];
    
    float videoParentWHPercent = rect.size.width / rect.size.height;
    
    CGSize remoteVideoSize = CGSizeZero;
    
    if(remoteSizeWHPercent > videoParentWHPercent) {
        remoteVideoSize = CGSizeMake(rect.size.width, rect.size.width / remoteSizeWHPercent);
    } else {
        remoteVideoSize = CGSizeMake(rect.size.height * remoteSizeWHPercent, rect.size.height);
    }
    
    CGRect remoteVideoRect = CGRectMake((rect.size.width - remoteVideoSize.width) / 2, (rect.size.height - remoteVideoSize.height) / 2, remoteVideoSize.width, remoteVideoSize.height);
    return remoteVideoRect;
}

-(UIView *)localView {
    if(!_localView) {
        CGRect viewRect = self.remoteView.frame;
        CGRect videoRect = CGRectMake(0, CGRectGetHeight(viewRect) / 3, CGRectGetHeight(viewRect) * (2 * 3) / (3 * 4), CGRectGetHeight(viewRect) * 2 / 3);
        _localView = [[UIView alloc] initWithFrame:videoRect];
        _localView.backgroundColor = [UIColor whiteColor];
        [_remoteView addSubview:_localView];
    }
    return _localView;
}

-(UIView *)remoteView {
    if(!_remoteView) {
        CGRect viewRect = self.videoParent.frame;
        CGRect videoRect = CGRectMake(0, 0, CGRectGetWidth(viewRect), CGRectGetHeight(viewRect));
        _remoteView = [[UIView alloc] initWithFrame:videoRect];
        _remoteView.backgroundColor = [UIColor clearColor];
        [self.videoParent addSubview:_remoteView];
        [self.videoParent bringSubviewToFront:self.overlayView];
    }
    return _remoteView;
}

-(UILabel *)information {
    if(!_information) {
        CGRect viewRect = self.localView.frame;
        _information = [[UILabel alloc] init];
        _information.frame = CGRectMake(0, 0,viewRect.size.width, viewRect.size.height / 7);
        _information.backgroundColor = [UIColor whiteColor];
        _information.font = [UIFont systemFontOfSize:18];
        _information.lineBreakMode = NSLineBreakByTruncatingMiddle;
        _information.textAlignment = NSTextAlignmentCenter;
        _information.textColor = [UIColor blackColor];
        _information.numberOfLines = 1;
    }
    return _information;
}

-(void)speak_disconnect:(BOOL)isAllow {
    [self allowSpeakInteraction:isAllow];
    
    [_localView removeFromSuperview];
    [_remoteView removeFromSuperview];
    _localView = nil;
    _remoteView = nil;
    _activityBtn.hidden = NO;
    
    [self stopConnectTimer];
}

- (void)allowSpeakInteraction:(BOOL)isAllow {
    //    NSLog(@"isAllow = %d",isAllow);
    if(isAllow) {
        _lianmaiAVBtn.hidden = NO;
        _lianmaiLabel.hidden = YES;
        _lianmaiLabel.text = @"视频连麦申请中";
        _disconnectLianmaiBtn.hidden = YES;
    } else {
        _lianmaiAVBtn.hidden = YES;
        _lianmaiLabel.hidden = NO;
        _lianmaiLabel.text = @"主播未开启连麦功能";
        _disconnectLianmaiBtn.hidden = YES;
    }
}

-(void)viewWillLayoutSubviews {
    if(_isLandscapeRight == true) {
        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
    }
}

- (void)customMessage:(NSString *)message {
    //    NSLog(@"message = %@",message);
}

@end
